﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCHelloworld.Models;

namespace MVCHelloworld.Controllers
{
    public class BookController : Controller
    {
        //
        // GET: /Book/
        BookDbContext db = new BookDbContext();
        public ActionResult Index()
        {
            var books = from b in db.Books
                       
                        select b;

            return View(books.ToList());
        }
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Book book)
        {
            if (ModelState.IsValid)
            {
                db.Books.Add(book);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
                return View(book);
        }

        public ActionResult Edit(int id)
        {
            Book book = db.Books.Find(id);
            if(book==null)
                return RedirectToAction("Index");
            return View(book);
        }
        [HttpPost]
        public ActionResult Edit(Book newBook)
        {
            try
            {
                Book oldBook = db.Books.Find(newBook.BookID);
                UpdateModel(oldBook);
                db.SaveChanges();
                return RedirectToAction("Details", new { id = newBook.BookID });
            }
            catch (Exception ex)
            {
            }
            return View(newBook);   
        }


        public ActionResult Details(int id)
        {
            Book book = db.Books.Find(id);
            if (book == null)
                return RedirectToAction("Index");

            return View(book);
        }
        public ActionResult Delete(int id)
        {
            Book book = db.Books.Find(id);
            if (book == null)
                return RedirectToAction("Index");

            return View(book);
        }

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            Book book = db.Books.Find(id);
            db.Books.Remove(book);
            db.SaveChanges();

            return RedirectToAction("Index");
        }
    }

}
